package com.flink.api.unit4;

import com.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * map_1
 *
 * @author caizhiyang
 * @since 2024-02-21
 */
public class flatMap_1 {

    /**
     * flatMap算子
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        DataStreamSource<WaterSensor> source = env.fromElements(
                new WaterSensor("sensor_1", 1L, 1),
                new WaterSensor("sensor_1", 11L, 11),
                new WaterSensor("sensor_2", 2L, 2),
                new WaterSensor("sensor_2", 12L, 12)
        );

        SingleOutputStreamOperator<String> singleOutputStreamOperator = source.flatMap(new FlatMapFunction<WaterSensor, String>() {

            @Override
            public void flatMap(WaterSensor waterSensor, Collector<String> collector) throws Exception {
                if (waterSensor.getId().equals("sensor_1")) {
                    //通过Collector.collect()来收集想要的结果，可以在流的下一步操作中获取
                    collector.collect("sensor_1 vc:" + String.valueOf(waterSensor.getVc()));
                } else if (waterSensor.getId().equals("sensor_2")) {
                    collector.collect("sensor_2 vc:" + String.valueOf(waterSensor.getVc()));
                    collector.collect("sensor_2 ts:" + String.valueOf(waterSensor.getTs()));
                }
            }
        });

        singleOutputStreamOperator.print();

        env.execute();
    }
}
